package com.yunze.iotapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yunze.apiCommon.utils.Arith;
import com.yunze.apiCommon.utils.VeDate;
import com.yunze.common.mapper.mysql.YzAgentPackageMapper;
import com.yunze.common.mapper.mysql.YzCardMapper;
import com.yunze.common.mapper.mysql.YzCardPacketMapper;
import com.yunze.common.mapper.mysql.YzOrderMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryIccidMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryMapper;
import com.yunze.common.mapper.mysql.card.YzApplicationforRenewalPrimaryOrdNoMapper;
import com.yunze.common.mapper.mysql.wechat.YzWxConfigMapper;
import com.yunze.iotapi.config.SysWxPayServiceInterface;
import com.yunze.iotapi.service.NewOpenApiService;
import com.yunze.iotapi.utils.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/10/09/15:14
 * @Description:
 */
@Slf4j
@Service
public class NewOPenApiServiceImpl implements NewOpenApiService {
    @Resource
    private YzCardMapper yzCardMapper;
    @Resource
    private YzAgentPackageMapper agentPackageMapper;
    @Resource
    private YzCardPacketMapper yzCardPacketMapper;
    @Resource
    private YzApplicationforRenewalPrimaryMapper renewalPrimaryMapper;
    @Resource
    private YzOrderMapper yzOrderMapper;
    @Resource
    private YzApplicationforRenewalMapper yzApplicationforRenewalMapper;
    @Resource
    private YzApplicationforRenewalPrimaryOrdNoMapper yzApplicationforRenewalPrimaryOrdNoMapper;
    @Resource
    private YzApplicationforRenewalPrimaryIccidMapper yzApplicationforRenewalPrimaryIccidMapper;
    @Resource
    private YzWxConfigMapper yzWxConfigMapper;
    @Resource
    private SysWxPayServiceInterface sysWxPayServiceInterface;

    @Override
    public Map<String, Object> queryCardInfoList(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.selectCardInfoList(iccid);
            //卡类型
            String prefix = iccid.substring(0, 6); // 提取前6位关键码
            // 判断中国电信
            if (prefix.startsWith("898603") || prefix.startsWith("898605") || prefix.startsWith("898611")) {
                cardInfoMaps.put("type", "中国电信");
            }
            // 判断中国移动
            else if (prefix.startsWith("898600") || prefix.startsWith("898602") || prefix.startsWith("898604") || prefix.startsWith("898607") || prefix.startsWith("898608")) {
                cardInfoMaps.put("type", "中国移动");
            }
            // 判断中国联通
            else if (prefix.startsWith("898601") || prefix.startsWith("898606") || prefix.startsWith("898609")) {
                cardInfoMaps.put("type", "中国联通");
            } else {
                cardInfoMaps.put("type", "其他");
            }
            if (!cardInfoMaps.containsKey("iccid") ||"".equals(cardInfoMaps.get("iccid"))) {
                cardInfoMaps.put("iccid",null);
            }
            if (!cardInfoMaps.containsKey("msisdn") ||"".equals(cardInfoMaps.get("msisdn"))) {
                cardInfoMaps.put("msisdn",null);
            }
            if (!cardInfoMaps.containsKey("imsi")||"".equals(cardInfoMaps.get("imsi"))) {
                cardInfoMaps.put("imsi",null);
            }
            if (!cardInfoMaps.containsKey("imei") || "".equals(cardInfoMaps.get("imei"))) {
                cardInfoMaps.put("imei",null);
            }
            if (!cardInfoMaps.containsKey("activateDate") || "".equals(cardInfoMaps.get("activateDate"))) {
                cardInfoMaps.put("activateDate",null);
            }
            if (!cardInfoMaps.containsKey("dueExpireTime") || "".equals(cardInfoMaps.get("dueExpireTime"))) {
                cardInfoMaps.put("dueExpireTime",null);
            }
            if (!cardInfoMaps.containsKey("status") || "".equals(cardInfoMaps.get("status"))) {
                cardInfoMaps.put("status",null);
            }
            if (!cardInfoMaps.containsKey("remarks") || "".equals(cardInfoMaps.get("remarks"))) {
                cardInfoMaps.put("remarks",null);
            }
            dataList.add(cardInfoMaps);
        }
        System.err.println(dataList);
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public Map<String, Object> queryCardDetail(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.selectCardDetail(iccid);
            if (!cardInfoMaps.containsKey("iccid") ||"".equals(cardInfoMaps.get("iccid"))) {
                cardInfoMaps.put("iccid",null);
            }
            if (!cardInfoMaps.containsKey("msisdn") ||"".equals(cardInfoMaps.get("msisdn"))) {
                cardInfoMaps.put("msisdn",null);
            }
            if (!cardInfoMaps.containsKey("imsi") ||"".equals(cardInfoMaps.get("imsi"))) {
                cardInfoMaps.put("imsi",null);
            }
            if (!cardInfoMaps.containsKey("useFlow") ||"".equals(cardInfoMaps.get("useFlow"))) {
                cardInfoMaps.put("useFlow",null);
            }
            if (!cardInfoMaps.containsKey("remaining") ||"".equals(cardInfoMaps.get("remaining"))) {
                cardInfoMaps.put("remaining",null);
            }
            if (!cardInfoMaps.containsKey("startTime") ||"".equals(cardInfoMaps.get("startTime"))) {
                cardInfoMaps.put("startTime",null);
            }
            if (!cardInfoMaps.containsKey("endTime") ||"".equals(cardInfoMaps.get("endTime"))) {
                cardInfoMaps.put("endTime",null);
            }
            if (!cardInfoMaps.containsKey("activateDate") ||"".equals(cardInfoMaps.get("activateDate"))) {
                cardInfoMaps.put("activateDate",null);
            }
            if (!cardInfoMaps.containsKey("status") ||"".equals(cardInfoMaps.get("status"))) {
                cardInfoMaps.put("status",null);
            }
            if (!cardInfoMaps.containsKey("packageName") ||"".equals(cardInfoMaps.get("packageName"))) {
                cardInfoMaps.put("packageName",null);
            }
            dataList.add(cardInfoMaps);
        }
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public Map<String, Object> queryCardPackage(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dataList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String, Object> cardInfoMaps = yzCardMapper.queryCardPackage(iccid);
            if (!cardInfoMaps.containsKey("iccid") ||"".equals(cardInfoMaps.get("iccid"))) {
                cardInfoMaps.put("iccid",null);
            }
            if (!cardInfoMaps.containsKey("msisdn") ||"".equals(cardInfoMaps.get("msisdn"))) {
                cardInfoMaps.put("msisdn",null);
            }
            if (!cardInfoMaps.containsKey("imsi") ||"".equals(cardInfoMaps.get("imsi"))) {
                cardInfoMaps.put("imsi",null);
            }
            if (!cardInfoMaps.containsKey("validateType") ||"".equals(cardInfoMaps.get("validateType"))) {
                cardInfoMaps.put("validateType",null);
            }
            if (!cardInfoMaps.containsKey("packageId") ||"".equals(cardInfoMaps.get("packageId"))) {
                cardInfoMaps.put("packageId",null);
            }
            if (!cardInfoMaps.containsKey("packetId") ||"".equals(cardInfoMaps.get("packetId"))) {
                cardInfoMaps.put("packetId",null);
            }
            if (!cardInfoMaps.containsKey("packetName") ||"".equals(cardInfoMaps.get("packetName"))) {
                cardInfoMaps.put("packetName",null);
            }
            dataList.add(cardInfoMaps);
        }
        System.err.println(dataList);
        return new ResponseJson().initSuccessOpen(dataList);
    }

    @Override
    public String mulCardStop(HttpServletRequest request) {
        return null;
    }

    @Override
    public String mulCardStart(HttpServletRequest request) {
        return null;
    }

    @Override
    //添加事务 回滚异常操作
    @Transactional
    public ResponseJson mulCardRenewal(HttpServletRequest request) {
        Map<String,Object> rMap = new HashMap<>();
        String map = (String) request.getAttribute("map");
        Map<String, Object> ParamMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) ParamMap.get("Param");
        Map<String, Object> verify = (Map<String, Object>) ParamMap.get("verify");
        //查询当前API登录用户agent_id
        Object appId = verify.get("appId");
        String agentId = agentPackageMapper.findAgentId(appId);
        //拿到iccid数组 资费组和资费计划
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);

        String packageId = null;
        String packetId = null;
        String validateType = null;
        try {
            packageId = param.get("packageId").toString();
            packetId = param.get("packetId").toString();
            validateType = param.get("validateType").toString();
        } catch (Exception e) {
            return new ResponseJson().initErrorOpen("500", "批量续费申请参数不能为空,请检查后重试！");
        }
        if (iccidList.size() > 500) {
            return new ResponseJson().initErrorOpen("500", "批量续费不得超过500张!");
        }
        //生成订单表信息 yz_order
        ResponseJson responseJson = this.generateTableInfo(iccidList, packageId, packetId, validateType, agentId);
        if (responseJson.get("status").equals("500")) {
            String errorMsg = (String) responseJson.get("message");
            return new ResponseJson().errorOpen("500", errorMsg);
        }
        Map<String, Object> cardPacket = null;
        //资费组和资费计划不能为空
        if (packageId != null && packageId.length() > 0 && packetId != null && packetId.length() > 0) {
            //生成主表信息
            //先查询续费资费计划 拿到资费计划单价
            cardPacket = yzCardPacketMapper.getPacketInfo(packetId);
            HashMap<Object, Object> hashMap = new HashMap<>();
            //校验是否有订单信息
            if (cardPacket == null) {
                return new ResponseJson().initErrorOpen("500", "该资费计划并没有订购信息，请检查后重试！");
            }
            hashMap.put("dept_id", agentId);
            hashMap.put("user_id", "1");
            hashMap.put("create_time", VeDate.getStringDate());
            hashMap.put("status", 0);
            hashMap.put("info", null);
            hashMap.put("is_send", 1);
            hashMap.put("card_sumCount", iccidList.size());
            hashMap.put("amount", Arith.mul(iccidList.size(), (Double) cardPacket.get("packet_price")));
            //生成主表信息
            renewalPrimaryMapper.insertPrimaryInfo(hashMap);
            //1.生成续费申请--资费计划表
            //参数准备 pid packet_info card_count
            Map<String, Object> findPacketMap = new HashMap<>();
            findPacketMap.put("dept_id", agentId);
            findPacketMap.put("packet_id", packetId);
            Map<String, Object> onePacket = yzCardPacketMapper.findOnePacket(findPacketMap);
            Map<String, Object> packetObj = new HashMap<>();
            packetObj.put("packet_info", JSON.toJSONString(onePacket));
            packetObj.put("card_count", iccidList.size());
            //插入主表id
            packetObj.put("p_id", hashMap.get("id"));
            packetObj.put("dept_id", agentId);
            packetObj.put("packet_wx_name", onePacket.get("packet_wx_name"));
            packetObj.put("packet_price", onePacket.get("packet_price"));
            packetObj.put("packet_flow", onePacket.get("packet_flow"));
            packetObj.put("packet_cost", onePacket.get("packet_cost"));
            packetObj.put("packet_valid_time", onePacket.get("packet_valid_time"));
            packetObj.put("packet_valid_name", onePacket.get("packet_valid_name"));
            packetObj.put("packet_id", onePacket.get("packet_id"));
            yzApplicationforRenewalMapper.insertRenewal(packetObj);
            for (String iccid : iccidList) {
                //2.生成续费--订单表
                //参数 订单号 主表id为p_id
                //查询订单号
                String orderNo = yzOrderMapper.selectOrderNo(iccid);
                HashMap<String, Object> orderMap = new HashMap<>();
                orderMap.put("ord_no", orderNo);
                orderMap.put("p_id", hashMap.get("id"));
                yzApplicationforRenewalPrimaryOrdNoMapper.insertOrderNo(orderMap);
                //3.生成续费--卡号表
                //参数 iccid 主表id为b_id b_id为yz_applicationfor_renewal的id
                yzApplicationforRenewalPrimaryIccidMapper.insertIccid(iccid, packetObj.get("id").toString());
            }
        } else {
            return new ResponseJson().initErrorOpen("500", "资费计划不能为空！");
        }
        rMap.put("packetName",cardPacket.get("packetName"));
        rMap.put("renewalStatus","审核中");
        rMap.put("iccidList",iccidList);
        return new ResponseJson().initSuccessOpen(rMap);
    }



    private ResponseJson generateTableInfo(List<String> iccidList, String packageId, String packetId, String validateType, String agentId) {
        for (String iccid : iccidList) {
            //卡必要信息
            Map<String, Object> cardInfo = yzCardMapper.getOneCardInfo(iccid);
            if (cardInfo == null) {
                return new ResponseJson().initErrorOpen("500", "卡号"+ iccid +"不存在,请检查信息！");
            }else {
                //资费计划信息
                Map<String, Object> packetInfo = yzCardPacketMapper.getOnePacketInfo(packageId, packetId);
                //生成订单
                this.insertOrderInfo(cardInfo, packetInfo, validateType);
            }
        }
        return new ResponseJson().successNewOpen(null);
    }

    private void insertOrderInfo(Map<String, Object> cardInfo, Map<String, Object> packetInfo, String validateType) {
        HashMap<String, Object> insertMap = new HashMap<>();
        String ord_no = com.yunze.common.utils.yunze.VeDate.getNo(8);
        insertMap.put("ord_no", ord_no);
        insertMap.put("ord_type", "2");
        insertMap.put("ord_name", "平台-批量充值");
        String iccid = cardInfo.get("iccid").toString();
        insertMap.put("iccid", iccid);
        insertMap.put("wx_ord_no", null);
        insertMap.put("status", "1");
        String price = packetInfo.get("packet_price").toString();
        insertMap.put("price", price);
        String packet_id = packetInfo.get("packet_id").toString();
        insertMap.put("packet_id", packet_id);
        insertMap.put("pay_type", "s");
        insertMap.put("cre_type", "sys");
        insertMap.put("is_profit", "0");
        insertMap.put("add_package", "0");
        insertMap.put("show_status", "0");
        insertMap.put("open_id", null);
        insertMap.put("agent_id", cardInfo.get("agent_id"));
        insertMap.put("profit_type", "0");
        insertMap.put("info", "API续费");
        insertMap.put("validate_type", validateType);
        insertMap.put("add_parameter", null);
        insertMap.put("is_audit", "0");
        insertMap.put("is_audi", "0");
        yzOrderMapper.insertOrder(insertMap);
    }

    /**
     * 查询修改后的数据--欣桥
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> queryDueExpireDateXQ(HttpServletRequest request) {
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        List<String> iccidList = JSONArray.parseArray(param.get("iccid").toString(), String.class);
        List<Object> dueExpireDateList = new ArrayList<>();
        for (String iccid : iccidList) {
            Map<String,Object>  dueExpireDateXQ = yzCardMapper.queryDueExpireDateXQ(iccid);
            dueExpireDateList.add(dueExpireDateXQ);
        }
        return new ResponseJson().initSuccessOpen(dueExpireDateList);
    }

    @Override
    public ResponseJson queryRenewalStatus(HttpServletRequest request) {
        //组装查询信息
        HashMap<String, Object> ReturnMap = new HashMap<>();
        String renewalStatus = "";
        String map = (String) request.getAttribute("map");
        Map<String, Object> paramMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) paramMap.get("Param");
        Integer renewalId = Integer.parseInt((String) param.get("renewalId"));
        Map<String, Object> renewalInfo = yzCardMapper.queryRenewalStatus(renewalId);
        Integer status = Integer.parseInt(renewalInfo.get("status").toString());
        //判断状态
        if (status == 0) {
            renewalStatus = "审核中";
        } else if (status == 1) {
            renewalStatus = "审核通过";
        } else {
            renewalStatus = "审核未通过";
        }
        //判断是否有反馈
        if ("".equals(renewalInfo.get("feedback")) || !renewalInfo.containsKey("feedback")) {
            ReturnMap.put("feedback", null);
        } else {
            ReturnMap.put("feedback", renewalInfo.get("feedback"));
        }
        ReturnMap.put("renewalId", renewalId);
        ReturnMap.put("renewalStatus", renewalStatus);
        return new ResponseJson().initSuccessOpen(ReturnMap);
    }

    @Transactional
    @Override
    public ResponseJson rechargeAccountForZSZF(HttpServletRequest request) {
        Map<String, Object> rMap = new HashMap<>();
        String map = (String) request.getAttribute("map");
        Map<String, Object> ParamMap = JSON.parseObject(map, new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> param = (Map<String, Object>) ParamMap.get("Param");
        Map<String, Object> verify = (Map<String, Object>) ParamMap.get("verify");
        //查询当前API登录用户agent_id
        Object appId = verify.get("appId");
        BigDecimal totalAmount = new BigDecimal(param.get("money").toString());
        Map<String, Object> agent = agentPackageMapper.findAgent(appId);
        String agentId = agent.get("appId").toString();
        String agentName = agent.get("agentName").toString();

        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = null;
        WxPayUnifiedOrderResult wxPayUnifiedOrderResult = null;
        String Message = "";
        String wx_appId = null;
        String nativeUrl = null;
        String codeUrl = "";
        String ord_no = "";
        String productId = String.valueOf(System.currentTimeMillis());
        try {
            //支付页面信息
            String body = "预存费用企业名称-" + agentName;

            Map<String, Object> findMap = new HashMap<>();
            findMap.put("agent_id", "100");
            Map<String, Object> wxConfig = yzWxConfigMapper.findOne(findMap);
            if (wxConfig == null) {
                Message = "未找到收款方，请联系管理员进行配置！";
            }
            //获取收款的 appid 统一默认为 平台代理 100
            wx_appId = wxConfig.get("app_id").toString();
            nativeUrl = wxConfig.get("native_url").toString();
            //请求支付的订单号和业务区分 时间戳加10位随机数
            ord_no = com.yunze.common.utils.yunze.VeDate.getNo(10);
            String time_end = com.yunze.common.utils.yunze.VeDate.getUserDateWithHalfHour("yyyyMMddHHmmss");
            //更新前先判断是否存在该账号 是则更新 否则新增
            int sum = yzOrderMapper.selectExistAgent(agentId);
            if (sum == 0) {
                //先新增账户
                yzOrderMapper.insertRenewalAccount(agentId, agentName);
                //新增充值表信息
                this.insertRechargeAccount(ord_no, agentId, agentName, totalAmount);
            } else {
                //增充值表信息
                this.insertRechargeAccount(ord_no, agentId, agentName, totalAmount);
            }
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(totalAmount));
            wxPayUnifiedOrderRequest = WxPayUnifiedOrderRequest
                    .newBuilder()
                    //订单号
                    .outTradeNo(ord_no)
                    //金额
                    .totalFee(yuanToFee(bigDecimal))
                    //描述
                    .body(body)
                    //ip
                    .spbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress())
                    .notifyUrl(nativeUrl)
                    .productId(productId)
                    //设置订单失效时间
                    .timeExpire(time_end)
                    .build();
            //微信支付参数初始化
            sysWxPayServiceInterface.afterPropertiesSet();
        } catch (NumberFormatException e) {
            log.error("微信支付开始调起异常 NumberFormatException----------------");
            log.error(e.getMessage());
        } catch (Exception e) {
            log.error("Exception " + e.getMessage());
        }
        try {
            wxPayUnifiedOrderResult = sysWxPayServiceInterface
                    .getWxPayService(wx_appId)
                    .unifiedOrder(wxPayUnifiedOrderRequest);
        } catch (WxPayException e) {
            log.error(e.getMessage());
            throw new RuntimeException("微信支付调起失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        codeUrl = wxPayUnifiedOrderResult.getCodeURL();
        rMap.put("codeUrl", codeUrl);
        rMap.put("orderNo", ord_no);
        return new ResponseJson().initSuccessOpen(rMap);
    }

    private void insertRechargeAccount(String ordNo, String agentId, String agentName, BigDecimal totalAmount) {
        if (ordNo != null) {
            HashMap<String, Object> insertMap = new HashMap<>();
            insertMap.put("order_no", ordNo);
            insertMap.put("total_money", totalAmount);
            insertMap.put("dept_id", agentId);
            insertMap.put("dept_name", agentName);
            yzOrderMapper.insertRechargeAccount(insertMap);
        }
    }

    /**
     * 描述： 1元钱转为 100分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }
}
